<template>
  <div class="pageRoll">
    <el-form
      :model="formModel"
      :rules="formRules"
      ref="formRef"
      label-width="100px"
    >
      <div class="navLine">基本信息</div>
      <div class="baseMsg">
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="formModel.name"
            style="width:550px"
            maxlength="30"
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="展示分类" prop="showCategoryIds">
          <el-select
            v-model="formModel.showCategoryIds"
            style="width:550px"
            multiple
            placeholder="请选择分类"
          >
            <el-option-group
              v-for="group in temShowList"
              :key="group.showCategoryId"
              :label="group.name"
            >
              <el-option
                v-for="item in group.showCategoryVos"
                :key="item.showCategoryId"
                :label="item.name"
                :value="item.showCategoryId"
              ></el-option>
            </el-option-group>
          </el-select>
          <el-button type="text" class="ml-20" @click="jumpClass(1)"
            >前往设置</el-button
          >
        </el-form-item>
        <el-form-item label="供应商">
          <el-select
            v-model="formModel.providerId"
            style="width:550px"
            placeholder="请选择供应商"
          >
            <el-option
              v-for="item in temSupList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button type="text" class="ml-20" @click="jumpClass(3)"
            >前往设置</el-button
          >
        </el-form-item>
        <el-form-item label="商品属性">
          <el-select
            v-model="formModel.attributeId"
            placeholder="请选择属性模板"
            style="width:550px"
            @change="selectTemAttsList"
          >
            <el-option
              v-for="item in temAttsList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button type="text" class="ml-20" @click="jumpClass(4)"
            >前往设置</el-button
          >
          <div class="valueName">
            <div class="flex between">
              <div>属性名称</div>
              <div>属性值</div>
              <div>操作</div>
            </div>
            <div
              class="valueName__noList"
              v-if="formModel.productAttributes.length === 0"
            >
              暂无数据~
            </div>
            <div
              class="valueName__List"
              v-for="(item, index) in formModel.productAttributes"
              :key="index"
              v-else
            >
              <el-input
                v-model="item.name"
                style="width:230px;"
                maxlength="10"
              ></el-input>
              <el-input
                v-model="item.value"
                style="width:230px;"
                maxlength="20"
              ></el-input>
              <div
                @click="formModel.productAttributes.splice(index, 1)"
                style="width:30px"
              >
                删除
              </div>
            </div>
          </div>
        </el-form-item>
        <el-button
          type="primary"
          plain
          style="margin-left:100px;margin-bottom:20px;"
          size="small"
          @click="addTemAtts"
          >+ 添加属性</el-button
        >
        <el-form-item label="商品大图" prop="widePic">
          <div class="product" style="display:flex">
            <el-upload
              class="productImg__uploader product__productImg"
              :auto-upload="false"
              :on-change="addUploadBigProductImg"
              action=""
              :show-file-list="false"
              style="width:250px;height:120px"
            >
              <img
                v-if="formModel.widePic"
                :src="formModel.widePic"
                class="product__productImg"
                style="width:250px;height:120px"
              />
              <i
                class="el-icon-plus product__productImg--uploader--icon"
                v-if="!formModel.widePic"
                style="width:250px;line-height:100px"
              ></i>
              <div
                class="product__productImg--uploader--add"
                v-if="!formModel.widePic"
                style="top:70px;left:100px"
              >
                添加图片
              </div>
            </el-upload>
          </div>
          <div class="text-info fs-12" style="color:rgba(69,64,60,0.6)">
            尺寸建议750x350（长方形模式）像素以上，大小1M以下
          </div>
        </el-form-item>
        <el-form-item label="商品视频">
          <div class="productVideo__uploader">
            <el-upload
              class="productImg__uploader product__productVideo"
              :auto-upload="false"
              :on-change="uploadProductVideo"
              action=""
              :show-file-list="false"
            >
              <video
                v-if="formModel.videoUrl !== ''"
                controls
                :src="formModel.videoUrl"
                style="width:100%;height:auto"
              ></video>
              <i
                v-else
                class="el-icon-plus product__productVideo--uploader--icon"
              ></i>
            </el-upload>
            <el-upload
              style="margin-left:20px"
              :auto-upload="false"
              action=""
              :on-change="uploadProductVideo"
              :show-file-list="false"
            >
              <el-button type="text">替换</el-button>
            </el-upload>
            <el-button
              type="text"
              style="margin-left:20px"
              class="fc-fe5f4b"
              @click="deleteVideoUrl"
              >删除</el-button
            >
          </div>
          <div class="text-info fs-12" style="color:rgba(69,64,60,0.6)">
            请上传5M以内的视图视频（该功能免费试用）
          </div>
        </el-form-item>
        <el-form-item label="商品主图" prop="pic">
          <div class="product" style="display:flex">
            <draggable v-model="productImgList">
              <div
                v-for="(item, index) in productImgList"
                :key="index"
                style="position:relative;margin-right:20px"
                class="product__productImg"
                draggable="true"
              >
                <el-upload
                  class="productImg__uploader product__productImg"
                  :auto-upload="false"
                  :on-change="uploadProductImg"
                  action=""
                  :show-file-list="false"
                >
                  <img
                    v-if="item.img"
                    :src="item.img"
                    @click="productImgIndex = index"
                    class="product__productImg"
                  />
                </el-upload>
                <div v-if="index === 0" class="productImg-text">封面图</div>
                <i
                  class="el-icon-circle-close productImg-icon"
                  v-if="item.img"
                  @click="cancelImg(item, index)"
                ></i>
              </div>
            </draggable>
            <el-upload
              class="productImg__uploader product__productImg"
              :auto-upload="false"
              :on-change="addUploadProductImg"
              action=""
              :show-file-list="false"
            >
              <i class="el-icon-plus product__productImg--uploader--icon"></i>
              <div class="product__productImg--uploader--add">添加图片</div>
            </el-upload>
          </div>
          <div class="text-info fs-12" style="color:rgba(69,64,60,0.6)">
            尺寸建议750x750（正方形模式）像素以上，大小1M以下，最多6张
            (可拖拽图片调整顺序 )
          </div>
        </el-form-item>
      </div>
      <div class="navLine">物流设置</div>
      <div class="sendMsg">
        <el-form-item label="配送方式" prop="distributionMode">
          <el-radio
            v-model="formModel.distributionMode"
            :label="0"
            @change="getLogModel"
            >商家配送</el-radio
          >
          <el-radio
            v-model="formModel.distributionMode"
            :label="1"
            style="margin-left:20px"
            @change="getLogModel"
            >快递配送</el-radio
          >
        </el-form-item>
        <el-form-item
          label="运费设置"
          prop="freightTemplateId"
          v-if="formModel.distributionMode === 1"
        >
          <el-select
            v-model="formModel.freightTemplateId"
            placeholder="请选择运费模板"
            @change="selectLogModel"
          >
            <el-option
              v-for="item in logModel"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button type="text" class="ml-20" @click="jumpClass(5)"
            >前往设置</el-button
          >
          <LogModel
            :templateId="formModel.freightTemplateId"
            ref="logRef"
            @getModelOption="getModelOption"
          ></LogModel>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Ref, Prop, Watch } from "vue-property-decorator";
import draggable from "vuedraggable";
import { upLoad } from "@/api/index";
import LogModel from "@/views/logistics/common/LogModel.vue";
import storage from "@/libs/storage";
import { readFile, advanceGetImage } from "@/store/modules/voidImg";

/*  */
import {
  getAllCategory,
  getAllAttsList,
  getLogistics,
  getAllSupList,
} from "@/api/good/goods";

/**
 * 编辑基本信息
 */
@Component({
  components: {
    draggable,
    LogModel,
  },
})
export default class GoodBaseInfo extends Vue {
  @Prop({
    type: Object,
    default() {
      return null;
    },
  })
  readonly goodDetail: any;

  @Ref()
  readonly logRef: HTMLFormElement;

  imageUrl = "";

  formModel = {
    /** 商品名称 */
    name: "",
    /** 展示分类id */
    showCategoryIds: [],
    /** 供应商ID */
    providerId: "",
    /** 供应商名称 */
    providerName: "",
    /** 商品属性模板id */
    attributeId: "",
    /** 模板属性 */
    attribute: "",
    /** 模板属性列表 */
    productAttributes: [],
    /** 商品图片 */
    albumPics: "",
    /** 展示图片 */
    pic: "",
    /** 商品视屏 */
    videoUrl: "",
    /** 配送方式 */
    distributionMode: 0,
    /** 运费模板ID */
    freightTemplateId: "",
    /** 商品分销设置 ?? */
    distributionSets: [],
    /** 货号 */
    productSn: "",
    widePic: "" as any,
  };

  /** 基本信息验证 */
  formRules = {
    name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
    showCategoryIds: [
      { required: true, message: "请选择分类", trigger: "change" },
    ],
    pic: [{ required: true, validator:((rule, value, callback)=>{
      if(!value){
        callback(new Error('请上传商品主图'));
      }else{
        callback();
      }
    }), trigger: "change" }],
    distributionMode: [
      {
        required: true,
        message: "请选择配送方式",
        trigger: "change",
      },
    ],
    freightTemplateId: [
      {
        required: true,
        message: "请选择物流模板",
        trigger: "change",
      },
    ],
  };

  /** 展示分类数组 */
  temShowList = [];

  /** 供应商数组 */
  temSupList = [];

  /** 属性模板数组 */
  temAttsList = [];

  /** 物流模板数组 */
  logModel = [] as any;

  /** 上传商品图片 */
  productImgList = [];

  /** 上传图片下标 */
  productImgIndex = 0;

  @Ref()
  readonly formRef: HTMLFormElement;

  mounted() {
    if (storage.get("formModel")) {
      this.formModel = storage.get("formModel");
      this.productImgList = this.getProductImgList(
        storage.get("formModel").albumPics,
      );
    }
    this.getTemShowList(); // 展示分类
    this.getTemAttsList(); // 属性模板
    this.getTemSupList(); // 供应商模板
    this.getLogis(); //  物流模板
  }

  /**
   * 还原表单数据
   */
  @Watch("goodDetail")
  setFormModel(nVal) {
    if (nVal) {
      const formModel = this.formModel;
      for (const key of Object.keys(formModel)) {
        const value = nVal[key];
        if (value) {
          formModel[key] = value;
        }
      }
      formModel.showCategoryIds = this.getShowCategoryIds(
        nVal.productShowCategorys,
      );
      formModel.freightTemplateId =
        formModel.freightTemplateId === "0" ? "" : formModel.freightTemplateId;
      this.productImgList = this.getProductImgList(nVal.albumPics);
    }
  }

  /**
   * 获取表单数据
   */
  async getFormModel() {
    try {
      this.setAlbumPics();
      await this.validate();
      // this.setSortingCategoryName();
      this.setProviderName();
      const formModel = this.formModel;
      const productShowCategorys = this.getProductShowCategorys();
      this.formModel.freightTemplateId =
        this.formModel.distributionMode === 0 ? "0" : this.logRef.templateId;
      return {
        ...formModel,
        productShowCategorys,
      };
    } catch (error) {
      console.log(error);
      return Promise.reject(false);
    }
  }

  /**
   * 对整个表单进行校验
   */
  validate() {
    return this.formRef.validate();
  }

  /**
   * 移除表单项的校验结果
   */
  clearValidate() {
    this.formRef.clearValidate();
  }

  /**
   * 获取展示分类
   */
  async getTemShowList() {
    const { data } = await getAllCategory({});
    this.temShowList = data || [];
  }

  /**
   * 获取展示分类
   */
  getProductShowCategorys() {
    const vals = this.formModel.showCategoryIds;
    const productShowCategorys = [];
    this.temShowList.forEach(item => {
      const productShowCategorySeconds = item.showCategoryVos.filter(child => {
        return vals.includes(child.showCategoryId);
      });
      if (productShowCategorySeconds.length) {
        const parentItem = {
          id: item.id,
          name: item.name,
          parentId: item.parentId,
          showCategoryId: item.showCategoryId,
          productShowCategorySeconds: productShowCategorySeconds.map(
            seconds => {
              return { ...seconds };
            },
          ),
        };
        productShowCategorys.push(parentItem);
      }
    });
    return productShowCategorys;
  }

  /**
   * 还原展示分类id
   */
  getShowCategoryIds(showCategorys = []) {
    let showCategoryId = [];
    showCategorys.forEach(item => {
      const ids = item.productShowCategorySeconds.map(
        child => child.showCategoryId,
      );
      showCategoryId = showCategoryId.concat(ids);
    });
    return showCategoryId;
  }

  /**
   * 获取供应商
   */
  async getTemSupList() {
    const { data } = await getAllSupList({});
    this.temSupList = data || [];
  }
  
  /**
   * 设置供应商名称
   */
  setProviderName() {
    const providerId = this.formModel.providerId;
    const currentTempSup = this.temSupList.find(item => item.id === providerId);
    this.formModel.providerName = currentTempSup ? currentTempSup.name : "";
  }

  /**
   * 获取商品属性
   */
  async getTemAttsList() {
    const { data } = await getAllAttsList({});
    this.temAttsList = data || [];
  }

  /**
   * 选择商品属性
   */
  selectTemAttsList(temAttsId: number) {
    const currenttemAtts = this.temAttsList.find(item => item.id === temAttsId);
    if (currenttemAtts) {
      this.formModel.attribute = currenttemAtts.name;
      this.formModel.productAttributes = currenttemAtts.attributeTemplates.map(
        item => {
          return {
            ...item,
            value: item.content,
          };
        },
      );
    }
  }

  /**
   * 添加商品属性
   */
  addTemAtts() {
    const obj = {
      content: "",
      name: "",
      id: "",
      parentId: "",
      value: "",
    };
    this.formModel.productAttributes.push(obj);
  }

  /**
   * 跳转分类/供货商/属性模板
   */
  async jumpClass(type) {
    let location = null;
    this.setAlbumPics();
    storage.set("formModel", this.formModel);
    // const model = await this.$parent.putAway(true);
    // console.log("this.formModel", model);
    // if (storage.get("formModel")) {
    //   storage.delete("formModel");
    //   storage.set("formModel", model);
    //   console.log("this.formModel22222222", model);
    // }
    // storage.set("formModel", model);
    storage.set("formModel", this.formModel);
    // return;
    this.$parent.$parent.$parent.$parent.saveFlag = true;
    switch (type) {
      case 1:
        location = { name: "calss", query: { options: "1" }, params: { options: "1" } };
        break;
      case 2:
        location = { name: "calss", query: { options: "2" }, params: { options: "2" } };
        break;
      case 3:
        location = { name: "sup", query: { options: "sup" }, params: { options: "sup" } };
        break;
      case 4:
        location = { name: "Attribute", query: { options: "pick" }, params: { options: "pick" } };
        break;
      case 5:
        location = { name: "logistics", query: { options: "log" }, params: { options: "log" } };
        break;
    }
    this.$router.push(location);
  }

  /**
   * @method uploadProductImg
   * @description 修改商品主图
   */
  async uploadProductImg(file) {
    const whiteList = ["image/jpeg", "image/jpg", "image/png"];

    const isLt1M = file.size < 1 * 1024 * 1024;
    if (!whiteList.includes(file.raw.type)) {
      this.$message.error("上传文件只能是 JPG或PNG 格式!");
      return;
    }
    if (!isLt1M) {
      this.$message.error("上传文件大小不能超过 1MB!");
      return;
    }

    const res = await upLoad({
      file: file.raw,
    });
    this.productImgList[this.productImgIndex].img = res.data;
    this.formRef.clearValidate('pic')
  }

  /**
   * 上传图片
   */
  async addUploadProductImg(file) {
    const whiteList = ["image/jpeg", "image/jpg", "image/png"];

    const isLt1M = file.size < 1 * 1024 * 1024;
    if (!whiteList.includes(file.raw.type)) {
      this.$message.error("上传文件只能是 JPG或PNG 格式!");
      return;
    }
    if (!isLt1M) {
      this.$message.error("上传文件大小不能超过 1MB!");
      return;
    }

    const res = await upLoad({
      file: file.raw,
    });
    this.productImgList.push({
      img: res.data,
    });
    this.formRef.clearValidate('pic')
  }

  /**
   * 上传大图片
   */
  async addUploadBigProductImg(file) {
    const whiteList = ["image/jpeg", "image/jpg", "image/png"];

    const isLt1M = file.size < 1 * 1024 * 1024;
    if (!whiteList.includes(file.raw.type)) {
      this.$message.error("上传文件只能是 JPG或PNG 格式!");
      return;
    }
    if (!isLt1M) {
      this.$message.error("上传文件大小不能超过 1MB!");
      return;
    }

    const imgFile = await readFile(file.raw);
    const newImg = await advanceGetImage(imgFile);
    if (newImg.image.width !== 750 || newImg.image.height !== 350) {
      this.$message.error("宽屏图片长宽应为750 * 350");
      return;
    }

    const res = await upLoad({
      file: file.raw,
    });
    this.formModel.widePic = res.data;
  }

  /**
   * 删除以选中图片
   */
  cancelImg(item, index) {
    this.productImgList.splice(index, 1);
    if(this.productImgList.length == 0){
      this.formModel.pic = ''
    }
  }

  /**
   *  设置商品图片
   */
  setAlbumPics() {
    const productImgList = this.productImgList;
    if (productImgList.length > 0) {
      this.formModel.pic = productImgList[0].img;
      this.formModel.albumPics = productImgList
        .filter(item => item.img !== "")
        .map(item => item.img)
        .join(",");
    }
  }

  /**
   * 还原商品图片
   */
  getProductImgList(albumPics = "") {
    const imgList = albumPics.split(",").map(item => {
      return { img: item };
    });
    return imgList;
  }

  /**
   * 上传视频
   */
  async uploadProductVideo(file) {
    const whiteList = ["video/mp4"];
    const isLt = file.size < 5 * 1024 * 1024;

    if (!whiteList.includes(file.raw.type)) {
      this.$message.error("上传视频只能是 mp4 格式!");
      return;
    }

    if (!isLt) {
      this.$message.error("上传视频大小不超过5M!");
      return;
    }

    const res = await upLoad({
      file: file.raw,
    });
    this.formModel.videoUrl = res.data;
  }

  /**
   * 删除视频
   */
  deleteVideoUrl() {
    this.formModel.videoUrl = "";
  }

  /**
   * 获取物流模板
   */
  async getLogis() {
    const res = await getLogistics({});
    this.logModel = res.data;
  }

  /**
   * 切换配送方式
   */
  getLogModel(e) {
    this.$parent.isWeight = false;
    if (e === 1) {
      this.formModel.freightTemplateId = "";
      this.$perent.logisticsId = "";
    }
  }

  /**
   * 选择物流模板
   */
  selectLogModel(e) {
    this.formModel.freightTemplateId = e;
    this.$parent.logisticsId = this.logRef.modelOption.id;
  }

  /**
   * 获取模板信息
   */
  getModelOption(modelOption) {
    this.$parent.isWeight = modelOption.valuationModel === 1 ? false : true;
  }
}
</script>
